package org.testis.communication.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

/**
 * A class to define a tcp server
 * @author nurhat
 */
public class AtofUdpServer {

    private DatagramSocket m_serverSocket;
    private int m_keepAliveTime;
    private int m_portNumber;
    private StringBuilder m_lastError;

    /**
     * Create udp server object
     * @param keepAliveTime defines timeout for waiting a client
     * @param portNumber
     */
    public AtofUdpServer(int keepAliveTime,
            int portNumber) {
        m_keepAliveTime = keepAliveTime;
        m_portNumber = portNumber;
        m_lastError = new StringBuilder();
    }

    /**
     * Waits a client for given timeout value.
     * Echos back any message recieved from a client
     * @return message of client and close its connection
     * @throws java.net.SocketException
     * @throws java.io.IOException
     */
    public String waitForClientMessage() {
        String result = null;
        try {
            m_serverSocket = new DatagramSocket(m_portNumber);
            m_serverSocket.setSoTimeout(m_keepAliveTime);
            m_serverSocket.setReuseAddress(true);
            result = readClientMsg();
        } catch (IOException ex) {
            m_lastError.append(ex.toString());
        } catch (Exception ex) {
            m_lastError.append(ex.toString());
        } finally {
            m_serverSocket.close();
        }
        return result;
    }

    private String readClientMsg() {
        byte[] buffer = new byte[1024];
        String result = null;
        try {
            DatagramPacket receivePacket =
                    new DatagramPacket(buffer,
                    buffer.length);
            m_serverSocket.receive(receivePacket);

            DatagramPacket sendPacket = new DatagramPacket(receivePacket.getData(),
                    receivePacket.getLength(),
                    receivePacket.getAddress(),
                    receivePacket.getPort());
            m_serverSocket.send(sendPacket);
            result = new String(receivePacket.getData(), "UTF-8");
            result = result.substring(0, receivePacket.getLength());
        } catch (SocketTimeoutException ex) {
            m_lastError.append("No client connected to server.Server timed out...");
        } catch (IOException ex) {
            m_lastError.append(ex.toString());
        } catch (Exception ex) {
            m_lastError.append(ex.toString());
        }
        return result;
    }

    /**
     * @return the m_lastError
     */
    public String getLastError() {
        return m_lastError.toString();
    }
}
